import { FC, useEffect, memo } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { useDispatch, useSelector, shallowEqual } from 'react-redux';
import { Helmet } from 'react-helmet';

import { AppState, AppThunk } from '../../store';
import { fetchUserListIfNeed } from '../../store/userList';
import { List } from '../../components/List';
import styles from './styles.module.scss';

export type Props = RouteComponentProps;

const Home: FC<RouteComponentProps> = () => {
  const dispatch = useDispatch<AppThunk>();

  const { readyStatus, items } = useSelector(({ userList }: AppState) => userList, shallowEqual);

  useEffect(() => {
    dispatch(fetchUserListIfNeed());
  }, [dispatch]);

  const renderList = () => {
    if (!readyStatus || readyStatus === 'invalid' || readyStatus === 'request') {
      return <div>Loading...</div>;
    }

    if (readyStatus === 'failure') {
      return <div>Error!</div>;
    }
    return <List items={items} />;
  };

  return (
    <div className={styles.Home}>
      <Helmet title="Home" />
      {renderList()}
    </div>
  );
};

export const loadData = (): AppThunk[] => [fetchUserListIfNeed()];

export default memo(Home)
